package com.micro.ai.auth.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.auth.annotation.AuditLogAnnotation;
import com.micro.ai.auth.entity.DictData;
import com.micro.ai.auth.service.DictDataService;
import com.micro.ai.commons.domain.ApiResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
import java.util.List;

/**
 * 字典数据控制器
 *
 * @author micro-ai
 * @since 2025-01-29
 */
@Slf4j
@RestController
@RequestMapping("/api/dict/data")
@Tag(name = "字典数据管理", description = "字典数据相关接口")
public class DictDataController {

    @Autowired
    private DictDataService dictDataService;

    /**
     * 分页查询字典数据
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询字典数据", description = "分页查询字典数据列表")
    @PreAuthorize("hasAuthority('dict:view')")
    public ApiResponse<IPage<DictData>> getDictDataPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "字典类型ID") @RequestParam(required = false) String dictTypeId,
            @Parameter(description = "字典标签") @RequestParam(required = false) String label,
            @Parameter(description = "字典值") @RequestParam(required = false) String value,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        
        Page<DictData> page = new Page<>(current, size);
        IPage<DictData> result = dictDataService.getDictDataPage(page, dictTypeId, label, value, status);
        
        return ApiResponse.success(result);
    }

    /**
     * 根据字典类型ID查询字典数据
     */
    @GetMapping("/type/{dictTypeId}")
    @Operation(summary = "根据字典类型查询数据", description = "根据字典类型ID查询字典数据")
    @PreAuthorize("hasAuthority('dict:view')")
    public ApiResponse<List<DictData>> getDictDataByType(@PathVariable String dictTypeId) {
        List<DictData> result = dictDataService.getByDictTypeId(dictTypeId);
        
        return ApiResponse.success(result);
    }

    /**
     * 根据字典类型编码查询字典数据
     */
    @GetMapping("/code/{dictTypeCode}")
    @Operation(summary = "根据编码查询字典数据", description = "根据字典类型编码查询字典数据")
    @PreAuthorize("hasAuthority('dict:view')")
    public ApiResponse<List<DictData>> getDictDataByCode(@PathVariable String dictTypeCode) {
        String tenantId = "tn_system"; // 暂时使用系统租户
        List<DictData> result = dictDataService.getByDictTypeCode(dictTypeCode, tenantId);
        
        return ApiResponse.success(result);
    }

    /**
     * 根据ID查询字典数据
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询字典数据详情", description = "根据ID查询字典数据详情")
    @PreAuthorize("hasAuthority('dict:view')")
    public ApiResponse<DictData> getDictDataById(@PathVariable String id) {
        DictData dictData = dictDataService.getById(id);
        if (dictData == null) {
            return ApiResponse.error("A0001", "字典数据不存在");
        }
        
        return ApiResponse.success(dictData);
    }

    /**
     * 创建字典数据
     */
    @PostMapping
    @Operation(summary = "创建字典数据", description = "创建新的字典数据")
    @PreAuthorize("hasAuthority('dict:create')")
    @AuditLogAnnotation(resourceType = "DICT_DATA", action = "CREATE")
    public ApiResponse<Boolean> createDictData(@Valid @RequestBody DictData dictData) {
        boolean result = dictDataService.createDictData(dictData);
        
        return ApiResponse.success(result);
    }

    /**
     * 更新字典数据
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新字典数据", description = "更新字典数据信息")
    @PreAuthorize("hasAuthority('dict:update')")
    @AuditLogAnnotation(resourceType = "DICT_DATA", action = "UPDATE")
    public ApiResponse<Boolean> updateDictData(@PathVariable String id, @Valid @RequestBody DictData dictData) {
        dictData.setId(id);
        boolean result = dictDataService.updateDictData(dictData);
        
        return ApiResponse.success(result);
    }

    /**
     * 删除字典数据
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除字典数据", description = "删除字典数据")
    @PreAuthorize("hasAuthority('dict:delete')")
    @AuditLogAnnotation(resourceType = "DICT_DATA", action = "DELETE")
    public ApiResponse<Boolean> deleteDictData(@PathVariable String id) {
        boolean result = dictDataService.deleteDictData(id);
        
        return ApiResponse.success(result);
    }

    /**
     * 批量删除字典数据
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除字典数据", description = "批量删除字典数据")
    @PreAuthorize("hasAuthority('dict:delete')")
    @AuditLogAnnotation(resourceType = "DICT_DATA", action = "DELETE")
    public ApiResponse<Boolean> batchDeleteDictData(@RequestBody List<String> ids) {
        boolean result = dictDataService.batchDeleteDictData(ids);
        
        return ApiResponse.success(result);
    }

    /**
     * 刷新字典缓存
     */
    @PostMapping("/refresh-cache/{dictTypeCode}")
    @Operation(summary = "刷新字典缓存", description = "刷新指定字典类型的缓存")
    @PreAuthorize("hasAuthority('dict:update')")
    public ApiResponse<Void> refreshDictCache(@PathVariable String dictTypeCode) {
        String tenantId = "tn_system"; // 暂时使用系统租户
        dictDataService.refreshDictCache(dictTypeCode, tenantId);
        
        return ApiResponse.success();
    }
}
